<template>
  <div class="app-container">
    <el-row class="search">
      <el-select
        v-model="query.t"
        style="margin-right: 8px; width: 120px"
        placeholder="日期类型"
      >
        <el-option
          v-for="item in [
            { label: '入院日期', value: '入院日期' },
            { label: '出院日期', value: '出院日期' },
          ]"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>

      <el-date-picker
        v-model="query.stime"
        style="width: 150px"
        type="date"
        placeholder="开始"
        value-format="yyyy-MM-dd"
        @change="stime_change"
      >
      </el-date-picker>
      <span>-</span>
      <el-date-picker
        style="width: 150px"
        v-model="query.etime"
        type="date"
        placeholder="结束"
        value-format="yyyy-MM-dd"
        @change="etime_change"
      >
      </el-date-picker>

      <el-select
        v-model="query.deptValue"
        style="margin-right: 8px; margin-left: 8px; width: 120px"
        placeholder="科室"
      >
        <el-option
          v-for="item in deptLs"
          :key="item.value"
          :label="item.text"
          :value="item.value"
        >
        </el-option>
      </el-select>

      <el-input
        v-model="query.s"
        prefix-icon="el-icon-search"
        style="width: 250px"
        :placeholder="searchText"
        @keyup.enter.native="search"
      ></el-input>

      <el-button type="warning" style="margin-left: 8px" @click="search" round
        >搜&nbsp;&nbsp;索</el-button
      >

      <el-button
        type="primary"
        style="margin-left: 8px"
        @click="generReport"
        round
        >生成报告</el-button
      >
    </el-row>

    <el-row>
      <el-table
        :data="
          ls2.slice(
            (disePathsPage - 1) * disePathsSize,
            disePathsPage * disePathsSize
          )
        "
        style="width: 100%"
        v-loading="isLoading"
        @row-dblclick="row_dblclick"
        highlight-current-row
        @sort-change="sort_change"
      >
        <el-table-column
          v-for="item in cols"
          :key="item"
          :label="item"
          :prop="item"
          fixed
          show-overflow-tooltip
          sortable
        >
        </el-table-column>

        <el-table-column :formatter="版本fmt" label="版本" sortable>
        </el-table-column>

        <el-table-column prop="评价例数" label="评价例数" sortable>
        </el-table-column>

        <el-table-column label="CMI" :formatter="fmt" sortable prop="CMI">
        </el-table-column>

        <el-table-column
          label="次均费用"
          :formatter="fmt"
          sortable
          prop="次均费用"
        >
        </el-table-column>

        <el-table-column
          label="费用消耗"
          :formatter="fmt"
          sortable
          prop="费用消耗"
        >
        </el-table-column>

        <el-table-column label="时间消耗">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              :content="
                比例(scope.row.床日, scope.row.病例数) +
                '/' +
                比例(scope.row.标杆床日, scope.row.病例数)
              "
              placement="right"
            >
              <span
                v-bind:class="{
                  ffred: IsRed(scope.row.床日, scope.row.标杆床日),
                  ffblue: IsBlue(scope.row.床日, scope.row.标杆床),
                }"
                >{{ 比例(scope.row.床日, scope.row.标杆床日) }}</span
              >
            </el-tooltip>
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="平均住院日"
          :formatter="fmt"
          prop="平均住院日"
          sortable
        >
        </el-table-column>

       

        <el-table-column
          label="次均药费"
          :formatter="fmt"
          prop="次均药费"
          sortable
        >
        </el-table-column>
        <el-table-column
          label="次均耗材费"
          :formatter="fmt"
          prop="次均耗材费"
          sortable
        >
        </el-table-column> -->

        <el-table-column label="药品消耗">
          <template slot-scope="scope">
            <el-link type="primary" @click="药品_click(scope.row, '药品')">
              <el-tooltip
                effect="dark"
                :content="
                  比例(scope.row.药品费, scope.row.病例数) +
                  '/' +
                  比例(scope.row.标杆药品费, scope.row.病例数)
                "
                placement="right"
              >
                <span
                  v-bind:class="{
                    ffred: IsRed(scope.row.药品费, scope.row.标杆药品费),
                  }"
                  >{{ 比例(scope.row.药品费, scope.row.标杆药品费) }}</span
                >
              </el-tooltip>
            </el-link>
          </template>
        </el-table-column>

        <el-table-column label="检验消耗">
          <template slot-scope="scope">
            <el-link type="primary" @click="药品_click(scope.row, '检验')">
              <el-tooltip
                class="item"
                effect="dark"
                :content="
                  比例(scope.row.检验费, scope.row.病例数) +
                  '/' +
                  比例(scope.row.标杆检验费, scope.row.病例数)
                "
                placement="right"
              >
                <span
                  v-bind:class="{
                    ffblue: IsBlue(scope.row.检验费, scope.row.标杆检验费),
                  }"
                  >{{ 比例(scope.row.检验费, scope.row.标杆检验费) }}</span
                >
              </el-tooltip>
            </el-link>
          </template>
        </el-table-column>

        <el-table-column label="检查消耗">
          <template slot-scope="scope">
            <el-link type="primary" @click="药品_click(scope.row, '检查')">
              <el-tooltip
                class="item"
                effect="dark"
                :content="
                  比例(scope.row.检查费, scope.row.病例数) +
                  '/' +
                  比例(scope.row.标杆检查费, scope.row.病例数)
                "
                placement="right"
              >
                <span
                  v-bind:class="{
                    ffblue: IsBlue(scope.row.检查费, scope.row.标杆检查费),
                  }"
                  >{{ 比例(scope.row.检查费, scope.row.标杆检查费) }}</span
                >
              </el-tooltip>
            </el-link>
          </template>
        </el-table-column>

        <el-table-column label="治疗消耗">
          <template slot-scope="scope">
            <el-link type="primary" @click="药品_click(scope.row, '治疗')">
              <el-tooltip
                class="item"
                effect="dark"
                :content="
                  比例(scope.row.治疗费, scope.row.病例数) +
                  '/' +
                  比例(scope.row.标杆治疗费, scope.row.病例数)
                "
                placement="right"
              >
                <span
                  v-bind:class="{
                    ffblue: IsBlue(scope.row.治疗费, scope.row.标杆治疗费),
                  }"
                  >{{ 比例(scope.row.治疗费, scope.row.标杆治疗费) }}</span
                >
              </el-tooltip>
            </el-link>
          </template>
        </el-table-column>

        <el-table-column label="耗材消耗">
          <template slot-scope="scope">
            <el-link type="primary" @click="药品_click(scope.row, '耗材')">
              <el-tooltip
                class="item"
                effect="dark"
                :content="
                  比例(scope.row.耗材费, scope.row.病例数) +
                  '/' +
                  比例(scope.row.标杆耗材费, scope.row.病例数)
                "
                placement="right"
              >
                <span
                  v-bind:class="{
                    ffred: IsRed(scope.row.耗材费, scope.row.标杆耗材费),
                  }"
                  >{{ 比例(scope.row.耗材费, scope.row.标杆耗材费) }}</span
                >
              </el-tooltip>
            </el-link>
          </template>
        </el-table-column>

        <el-table-column label="手术消耗">
          <template slot-scope="scope">
            <el-tooltip
              class="item"
              effect="dark"
              :content="
                比例(scope.row.手术费, scope.row.病例数) +
                '/' +
                比例(scope.row.标杆手术费, scope.row.病例数)
              "
              placement="right"
            >
              <span
                v-bind:class="{
                  ffred: IsRed(scope.row.手术费, scope.row.标杆手术费),
                }"
                >{{ 比例(scope.row.手术费, scope.row.标杆手术费) }}</span
              >
            </el-tooltip>
          </template>
        </el-table-column>

        <!-- <el-table-column label="平均得分" sortable>
          <template scope="scope">
            {{
              ((scope.row.得分 / (scope.row.评分人次 || 1)) * 1.0).toFixed(2)
            }}
          </template>
        </el-table-column> -->
      </el-table>

      <div class="block">
        <el-pagination
          @size-change="disePathsbasicCostHandleSizeChange"
          @current-change="disePathsbasicCostCurrentChange"
          :current-page="disePathsPage"
          :page-sizes="[5, 10, 20, 50, 100, 200, 300, 400]"
          :page-size="disePathsSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-row>

    <el-row>
      <el-dialog
        placement="left"
        :title="
          项目Row.科室 + '-' + 项目Row.医生 + '-' + (项目Row.病组编码 || '')
        "
        :visible.sync="项目Vble"
        width="600"
      >
        <el-table :data="药品Ls" v-loading="药品Loading">
          <el-table-column label="名称">
            <template slot-scope="scope">
              <el-tooltip
                :content="scope.row.药品说明"
                placement="top"
                popper-class="atooltip"
                v-if="scope.row.药品说明"
              >
                <span style="color: red">{{ scope.row.名称 }}</span>
              </el-tooltip>
              <span v-else>{{ scope.row.名称 }}</span>
            </template>
          </el-table-column>
          <el-table-column
            v-if="药品规格显示"
            property="规格"
            label="规格"
          ></el-table-column>
          <el-table-column
            property="医保类型"
            label="医保类型"
          ></el-table-column>
          <el-table-column
            property="单价"
            label="单价"
            width="100"
          ></el-table-column>
          <el-table-column
            property="数量"
            label="数量"
            width="100"
          ></el-table-column>
          <el-table-column
            property="金额"
            label="金额"
            width="100"
          ></el-table-column>
          <el-table-column
            :formatter="人均花费_fmt"
            label="人均花费"
            width="100"
          ></el-table-column>
        </el-table>
      </el-dialog>
    </el-row>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from "vue-property-decorator";
import { Format } from "@/utils/Utils";
import { dept } from "@/api/patient";
import { costLs, medcTop } from "@/api/report";
import { getVersionName } from "@/utils/Utils";
import { getNormalizedDate } from "handsontable/helpers";
import axios from "axios";
import { UserModule } from "@/store/modules/user";
@Component({
  name: "clinicalpathway-dgpe",
})
export default class extends Vue {
  //private grp = "分组编码,分组名称";
  private query = {
    stime: "",
    etime: Format("yyyy-MM-dd", new Date()),
    s: "",
    grp: "病组编码,病组名称,科室,医生",
    size: 10,
    currentPage: 1,
    o: "病例数",
    deptValue: "",
    x: "DESC",
    order: "",
    w: "",
    t: (<any>window).MyConf["DataType"] || "出院日期",
    comapny: (<any>window).MyConf["Company"],
  };

  private total = 0;
  private disePathsSize = 10;
  private disePathsPage = 1;
  private disePathsbasicCostHandleSizeChange(val: number) {
    this.disePathsSize = val;
    this.disePathsPage = 1;
    this.query.size = val;
    this.costLs();
  }
  private disePathsbasicCostCurrentChange(val: number) {
    this.disePathsPage = val;
    this.query.currentPage = val;
    //this.selectRow();
  }

  private stime_change(val: any) {
    localStorage.setItem("stime", val);
  }
  private etime_change(val: any) {
    localStorage.setItem("etime", val);
  }
  private 人均花费_fmt(row: any) {
    return (row.金额 / row.人数).toFixed(2);
  }
  private 版本fmt(row: any) {
    return getVersionName(row.病组编码);
  }

  // private 比例(v1: number, v2: number, c: string) {
  //   let r = (v1 / v2) * 1.0;

  //   if (r == Infinity) {
  //     return "∞";
  //   }

  //   if (isNaN(r)) {
  //     return "";
  //   }
  //   return r.toFixed(2);
  // }

  private row_dblclick(r: any) {
    this.$router.push({
      path: "/clinicalpathway/user",
      query: {
        c: "病组编码",
        s: r.病组编码,
        deptValue: r.科室,
        doctorValue: r.医生,
        t: this.query.t,
        stime: this.query.stime,
        etime: this.query.etime,
        st: "是否评估",
      },
    });
  }

  private 药品Ls: Array<any> = [];
  private 药品Loading: boolean = false;

  private 项目Row: any = {};
  private 项目Vble: boolean = false;

  private async 项目TopN(r: any, pt: any) {
    this.药品Loading = true;
    this.项目Vble = !this.项目Vble;
    this.项目Row = r;
    let d = await medcTop({
      stime: this.query.stime,
      etime: this.query.etime,
      ks: r.科室,
      code: r.病组编码,
      doc: r.医生,
      t: this.query.t,
      ts: 5,
      pt: pt,
    });
    this.药品Loading = false;
    return d.data;
  }
  private 药品规格显示: boolean = false;
  private async 药品_click(r: any, t: string) {
    this.药品规格显示 = t == "药品";
    this.药品Ls = await this.项目TopN(r, t);
  }
  private sort_change(r: any) {
    let tmps = JSON.parse(JSON.stringify(this.ls));
    tmps.sort((a: any, b: any) => {
      let v = a[r.prop] - b[r.prop];
      if (!r.order.startsWith("asc")) {
        v *= -1;
      }
      return v;
      //return a[r.prop] - b[r.prop];
    });

    this.ls2 = tmps;
    //this.disePathsPage = 1;
  }
  private fmt(row: any, col: any, val: number) {
    // if (!val) return "";
    if (!val) return "";

    return val.toFixed(2);
  }
  private IsRed(v1: number, v2: number) {
    let r = (v1 / v2) * 1.0;

    if (r > 1.2) return true;

    return false;
  }
  private 比例(v1: number, v2: number, c: string) {
    let r = (v1 / v2) * 1.0;

    if (r == Infinity) {
      return "∞";
    }

    if (isNaN(r)) {
      return "0";
    }
    return r.toFixed(2);
  }

  // private fmt(row: any, col: any, val: any) {
  //   if (!val) return val;

  //   return val.toFixed(2);
  // }
  private deptLs: Array<any> = [];

  public async dept() {
    let curDate = new Date();
    let t = `${Format("yyyyMMddh", curDate)}${parseInt(
      curDate.getMinutes() / 5 + ""
    )}`;
    let d: any = await dept({ t: t });
    d = d.data || [];
    this.deptLs = [
      { text: "所有科室", value: "" },
      ...d.map((it: any) => ({ text: it, value: it })),
    ];
  }

  private search() {
    this.disePathsPage = 1;
    this.costLs();
    // this.costLs();
  }

  private generReport() {
    //显示进度
    this.isLoading = true;
    let q = JSON.parse(JSON.stringify(this.query));
    q.stime += " 00:00:00";
    q.etime += " 23:59:59";

    axios({
      method: "POST",
      baseURL: `${(<any>window).MyConf.APISERVICE}`,
      url: "/report/word",
      headers: { "X-Access-Token": UserModule.token },
      data: q,
      responseType: "blob", //返回是个文件
    }).then((response) => {
      // download(response, data); //then直接下载，方法在下边
      this.download(response);
      //隐藏进步
      this.isLoading = false;
    });
  }
  private download(res: any) {
    let blob = new Blob([res.data], { type: "application/vnd.ms-word" }); //type是文件类，详情可以参阅blob文件类型
    // 创建新的URL并指向File对象或者Blob对象的地址
    const blobURL = window.URL.createObjectURL(blob);
    // 创建a标签，用于跳转至下载链接
    const tempLink = document.createElement("a");
    tempLink.style.display = "none";
    tempLink.href = blobURL;
    tempLink.setAttribute("download", `临床路径报告.docx`);
    // 兼容：某些浏览器不支持HTML5的download属性
    if (typeof tempLink.download === "undefined") {
      tempLink.setAttribute("target", "_blank");
    }
    // 挂载a标签
    document.body.appendChild(tempLink);
    tempLink.click();
    document.body.removeChild(tempLink);
    // 释放blob URL地址
    window.URL.revokeObjectURL(blobURL);
  }

  private created() {
    let cDate = new Date();
    let m =
      cDate.getMonth() - parseInt((<any>window).MyConf["TIMEINTERVAL"] || "1");
    cDate.setMonth(m);

    if (!this.query.stime) {
      this.query.stime = Format("yyyy-MM-dd", cDate);
    }

    this.cols = this.query.grp.split(",");
    this.grpChange();

    this.dept();

    this.costLs();
  }

  private ls: Array<any> = [];
  private ls2: Array<any> = [];
  private cols: Array<any> = this.query.grp.split(",");

  private searchText = "";
  private grpChange() {
    this.searchText = this.query.grp
      .split(",")
      .map((it: string) => `${it}`)
      .join("、");
  }

  private isLoading: boolean = true;
  private async costLs() {
    this.isLoading = true;
    // if (!this.grp || this.grp.length == 0) return;

    this.query.grp = this.query.grp;

    this.query.order = `${this.query.o} ${this.query.x}`;

    // if (!this.query.w) this.query.w = "1=1";
    this.query.w = "是否评估=1";
    if (this.query.deptValue) {
      this.query.w += ` AND 科室='${this.query.deptValue}'`;
    }
    //分组编码不能为空
    // if (this.query.w.indexOf("分组编码") < 0) {
    //   this.query.w = "分组编码 IS NOT NULL AND " + this.query.w;
    // }
    if (this.query.s) {
      let p = this.cols
        .map((it: any) => `${it} like '${this.query.s}'`)
        .join(" OR ");
      this.query.w += ` AND (${p})`;
    }
    let q = JSON.parse(JSON.stringify(this.query));
    q.stime = q.stime + " 00:00:00";
    q.etime = q.etime + " 23:59:59";
    let res: any = await costLs(q);
    let d = res.data;
    this.ls = d;
    this.resetData(this.ls);
    this.ls2 = JSON.parse(JSON.stringify(this.ls));
    this.total = res.total || d.length;
    this.isLoading = false;
  }

  private resetData(ls: any) {
    ls.forEach((it: any) => {
      it.次均费用 = (it.总费用 / it.病例数) * 1.0;
      it.平均住院日 = (it.床日 / it.病例数) * 1.0;
      it.次均药费 = (it.药品费 / it.病例数) * 1.0;
      it.次均耗材费 = (it.耗材费 / it.病例数) * 1.0;
    });
  }

  // private grps: Array<any> = ["模板名称,版本号,科室,医生"];

  private grpIndex = 0;

  private IsBlue(v1: number, v2: number) {
    let r = (v1 / v2) * 1.0;

    if (r < 0.8) return true;

    return false;
  }
}
</script>

<style lang="scss">
.red {
  color: red;
}

.blue {
  color: blue;
}

.el-link {
  text-decoration: underline;
}
</style>
